package cn.zcib.tms.web;

import cn.zcib.tms.dao.*;
import cn.zcib.tms.model.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.reflection.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;


@Controller
public class BackgroundController {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private RouteMapper routeMapper;
    @Autowired
    private SourceMapper sourceMapper;
    @Autowired
    private ServiceMapper serviceMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Value("${upload}")
    private String imagePath;

    @Value("${pageSize}")
    private int pageSize;

    @GetMapping("/manager/{url}")
    public String url(@Validated String url) {
        return url;
    }


    @GetMapping("/manager/")
    public String index() {
        return "manager/index";
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////
    //dpp
    @RequestMapping(value = "/manager/add", method = RequestMethod.POST)
    public String addShop(Shop shop, @RequestParam("image") MultipartFile file,
                          HttpServletRequest request) throws IOException {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        File targetFile = new File(request.getServletContext().getRealPath("upload/"));
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        shop.setSh_image_pre("/upload/" + fileName);
        System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);
        System.out.println(shop);
        FileOutputStream out = new FileOutputStream(targetFile.getPath() + "/" + fileName);
        shopMapper.addShop(shop);
        out.write(file.getBytes());
        out.flush();
        out.close();
        System.out.println("contentType:" + contentType + "fileName:" + targetFile.getPath() + fileName);
        return "redirect:/manager/shop";//重定向到全部shop
    }

    @RequestMapping("/manager/delete")
    public String deleteShop(Integer sh_id) {
        shopMapper.deleteShop(sh_id);
        return "redirect:/manager/shop";
    }

    @RequestMapping("/manager/shop/update")
    public void updateShop(Shop shop) {
        System.out.println(shop.toString());
        shopMapper.updateShop(shop);
    }

    @RequestMapping("/manager/shop")
    public String fingAllShop(@RequestParam(defaultValue = "0") Integer type, @RequestParam(defaultValue = "") String key, @RequestParam(defaultValue = "1") Integer currentPage, Model model) {
        List<Shop> list = null;
        PageHelper.startPage(currentPage, 5);//currentPage:当前页   pageSize：页大小
        if (key == null && key.trim().isEmpty()) {
            list = shopMapper.shop(type, null);
        } else {
            list = shopMapper.shop(type, key);
        }
        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("key", key);
        model.addAttribute("type", type);
        return "manager/shopList";
    }

    //模糊查询
    @RequestMapping("/manager/findShopByKey")
    public String fingShop(@RequestParam(defaultValue = "0") Integer type, @RequestParam(defaultValue = "") String key, @RequestParam(defaultValue = "1") Integer currentPage, Model model) {
        List<Shop> list = null;
        PageHelper.startPage(currentPage, 5);//currentPage:当前页   pageSize：页大小
        if (key == null && key.trim().isEmpty()) {
            list = shopMapper.shop(type, null);
        } else {
            list = shopMapper.findShop(key);
        }
        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("key", key);
        model.addAttribute("type", type);
        return "manager/shopList";
    }

    ////////////////////路线////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////
    @RequestMapping("addRoute")
    public void addRoute(Route route) {
        if (route.getR_route() != null && route.getR_route().trim() != null && route.getR_station()
                != null && route.getR_station().trim() != null && route.getR_type() != null) {
            routeMapper.addRoute(route);
        }
    }

    @RequestMapping("/manager/findAllRoute")
    public String findAllRoute(@RequestParam(defaultValue = "1") Integer currentPage, Model model) {
        PageHelper.startPage(currentPage, 2);
        List<Route> list = routeMapper.findAllRoute();

        PageInfo<Route> pageInfo = new PageInfo<>(list);
        System.out.println("page::" + pageInfo);
        model.addAttribute("pageInfo", pageInfo);
        return "manager/routeList";
    }

    /**
     * 查询所有的旅行资源
     *
     * @param currentPage
     * @param type
     * @param key
     * @param model
     * @return
     */
    @RequestMapping("/manager/travelResources")
    public String travelResources(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "1") Integer type, String key, Model model) {
        List<Source> list = null;
        System.out.println("currentPage:" + currentPage + "type:" + type + "key:" + key);

        PageHelper.startPage(currentPage, 10);
        if (key == null) {
            list = sourceMapper.findAllSource(type, null);
            System.out.println("list:" + list);
        } else {
            list = sourceMapper.findAllSource(type, key);
        }
        PageInfo<Source> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("type", type);
        model.addAttribute("key", key);
        System.out.println(pageInfo);
        return "manager/sourceList";
    }

    @RequestMapping("/manager/source/add")
    public String addSource(Source source, @RequestParam("image") MultipartFile file,
                            HttpServletRequest request) throws IOException {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        File targetFile = new File(request.getServletContext().getRealPath(imagePath));
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        source.setSo_image_pre("/upload/" + fileName);
        System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);
        System.out.println(source);
        FileOutputStream out = new FileOutputStream(targetFile.getPath() + "/" + fileName);
        sourceMapper.addSource(source);
        out.write(file.getBytes());
        out.flush();
        out.close();
        System.out.println("contentType:" + contentType + "fileName:" + targetFile.getPath() + fileName);
        return "redirect:/manager/travelResources";
    }

    ////////////////////////////服务设施/////////////////////////////////////////////
    @RequestMapping("/manager/service")
    public String findServiceByType(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "1") Integer type, @RequestParam(defaultValue = "") String key, Model model) {
        PageHelper.startPage(currentPage, 2);
        List<Service> list = serviceMapper.findAllService(type, key);

        PageInfo<Service> pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("key", key);
        model.addAttribute("type", type);
        return "/manager/serviceList";
    }

    @RequestMapping("/manager/service/add")
    public String addService(Service service, @RequestParam("image") MultipartFile file,
                             HttpServletRequest request) throws IOException {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        File targetFile = new File(request.getServletContext().getRealPath(imagePath));
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        service.setSe_image_pre("/upload/" + fileName);
        System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);
        System.out.println(service);
        FileOutputStream out = new FileOutputStream(targetFile.getPath() + "/" + fileName);
        serviceMapper.addService(service);
        out.write(file.getBytes());
        out.flush();
        out.close();
        System.out.println("contentType:" + contentType + "fileName:" + targetFile.getPath() + fileName);
        return "redirect:/manager/service";
    }

    @RequestMapping("/manager/service/del")
    public String deleteService(String id) {
        serviceMapper.deleteService(id);
        return "redirect:/manager/service";
    }


    ////////////////////////////预定管理/////////////////////////////////////////////

    /**
     * 查询所有预订信息
     *
     * @param flag
     * @param currentPage
     * @param request
     * @return
     */
    @RequestMapping("/manager/order")
    public String findOrdersByFlag(@RequestParam(defaultValue = "0") Integer flag, @RequestParam(defaultValue = "1") Integer currentPage, HttpServletRequest request) {
        PageHelper.startPage(pageSize, currentPage);
        List<Orders> orders = orderMapper.findOrdersByFlag(flag);

        PageInfo pageInfo = new PageInfo(orders);
        request.setAttribute("pageInfo", pageInfo);
        return "/manager/orderList";
    }


    @RequestMapping("/manager/checked")
    public String  checkedOrder(Integer o_id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(o_id == null){
            request.setAttribute("message","请指定所要确认的订单！");
            request.getRequestDispatcher("/manager/order").forward(request,response);
            return null;
        }else{
            orderMapper.checkedOrder(o_id,1);
            return "redirect:/manager/order";
        }

    }


    ////////////////////////////修改操作/////////////////////////////////////////////

    /**
     * 查询资源详情
     *
     * @param flag
     * @param currentPage
     * @param request
     * @return
     */
    /**
     * 显示服务设施信息
     *
     * */
    @GetMapping("/updateSource")
    public String findSourceInfo(@RequestParam(defaultValue = "0") String id, Model model) {
        Source source = sourceMapper.findSourceById(id);
//        List<Route> routes = routeMapper.findRouteByTypeId("1",id);
//        service.setRoutes(routes);
        System.out.println(source);
//        model.addAttribute("category","service");
        model.addAttribute("info",source);
        return "updateSource";
    }


    @GetMapping("/updateService")
    public String findServiceInfo(@RequestParam(defaultValue = "0") String id, Model model) {
        Service service = serviceMapper.findServiceById(id);
        System.out.println(service);
        model.addAttribute("info",service);
        return "updateService";
    }


}
